package gre.core;

import gre.db.*;
import java.sql.*;
import java.util.*;

/**
 *
 * @author nacuong
 */
public class WordSelector {

  /**
   * Return all words, meaning and sentences data from database
   * @param stmt
   * @return a vector which contains vector of words, meaning and sentences. The inner vector has first and second
   *        element as the word and its meaning, while the rest are sentences.
   * @throws SQLException
   */
  public static Vector<Vector<String>> selectAll(Statement stmt) throws SQLException {
    Vector<Vector<String>> datas = new Vector<Vector<String>>();

    ResultSet results = stmt.executeQuery("Select wid from words");
    Vector<Integer> wordIds = new Vector<Integer>();
    while (results.next()) {
      wordIds.add(results.getInt("wid"));
    }

    for (int wordId : wordIds) {
      Vector<String> data = selectWord(stmt, wordId);
      if (!data.isEmpty()) {
        datas.add(data);
      }
    }

    return datas;
  }

  /**
   * Find meaning and sentences for a given word.
   * @param stmt sql statement executor
   * @param word word to search for
   * @return a vector string whose first and second elements are the word and its meaning; the rest are its sentences;
   *         return an empty vector if the word cannot be found.
   * @throws SQLException
   */
  public static Vector<String> selectWord(Statement stmt, String word) throws SQLException {
    int wordId = DBSelector.selectId(stmt, word);
    return selectWord(stmt, wordId);
  }

  /**
   * Find meaning and sentences for a given word id.
   * @param stmt sql statement executor
   * @param word word to search for
   * @return a vector string whose first and second elements are the word and its meaning; the rest are its sentences;
   *         return an empty vector if the word cannot be found.
   * @throws SQLException
   */
  public static Vector<String> selectWord(Statement stmt, int wordId) throws SQLException {
    Vector<String> data = new Vector<String>();
    String word = DBSelector.selectWord(stmt, wordId);
    String meaning = DBSelector.selectMeaning(stmt, wordId);
    Vector<String> sentences = DBSelector.selectStatement(stmt, wordId);
    if (word != null) {
      data.add(word);
      data.add(meaning);
      data.addAll(sentences);
    }

    return data;
  }

  /**
   * Display a vector of data word, meaning, sentence
   * in form of string word|meaning|sentence1@sentence2...
   * @param data
   */
  public static String displayWord(Vector<String> data) {
    String line = "Cannot find this word.";
    if (data.size() >= 2) {
      String word = data.get(0);
      String meaning = data.get(1);
      line = word + "|" + meaning + "|";
      for (int inx = 2; inx < data.size(); inx++) {
        line += data.get(inx);
        if (inx != data.size() - 1) {
          line += "@";
        }
      }
    }

    return line;
  }
}
